// Fill out your copyright notice in the Description page of Project Settings.


#include "HotChunkJsonHttp.h"
#include "HttpModule.h"
#include "Interfaces/IHttpResponse.h"
#include "Misc/FileHelper.h"

UHotChunkJsonHttp* UHotChunkJsonHttp::Get()
{
	static UHotChunkJsonHttp* HotChunkJsonHttp;
	if (!HotChunkJsonHttp)
	{
		HotChunkJsonHttp = NewObject<UHotChunkJsonHttp>();
		HotChunkJsonHttp->AddToRoot();
	}
	return HotChunkJsonHttp;
}

void UHotChunkJsonHttp::RequireDownLoad(const FString& Url, const TBaseDelegate<void, FString, bool>& RequestComplete, const FHttpRequestProgressDelegate& RequestProgress)
{
	if (RequestingMap.Contains(Url))
	{
		TSharedPtr<FHotChunkJsonHttpRequest> HotChunkJsonHttpRequest = *RequestingMap.Find(Url);
		HotChunkJsonHttpRequest->JsonHttpComplete.Add(RequestComplete);
		HotChunkJsonHttpRequest->JsonHttpProgress.Add(RequestProgress);
		return;
	}

	FHttpRequestPtr HttpRequest = FHttpModule::Get().CreateRequest();
	HttpRequest->SetURL(Url);
	HttpRequest->SetVerb(TEXT("GET"));
	HttpRequest->SetHeader(TEXT("Content-Type"), TEXT("application/json"));
	HttpRequest->OnProcessRequestComplete().BindUObject(this, &UHotChunkJsonHttp::OnRequestComplete);
	HttpRequest->OnRequestProgress().BindUObject(this, &UHotChunkJsonHttp::OnRequestProgress);

	TSharedPtr<FHotChunkJsonHttpRequest> NewHotChunkJsonHttpRequest = MakeShareable(new FHotChunkJsonHttpRequest(HttpRequest));
	NewHotChunkJsonHttpRequest->JsonHttpComplete.Add(RequestComplete);
	NewHotChunkJsonHttpRequest->JsonHttpProgress.Add(RequestProgress);
	RequestingMap.Add(Url, NewHotChunkJsonHttpRequest);

	HttpRequest->ProcessRequest();
}

void UHotChunkJsonHttp::OnRequestComplete(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool IsSucceeded)
{
	TSharedPtr<FHotChunkJsonHttpRequest> HotChunkJsonHttpRequest = *RequestingMap.Find(HttpRequest->GetURL());
	HotChunkJsonHttpRequest->JsonHttpComplete.Broadcast(HttpResponse->GetContentAsString(), IsSucceeded);
	RequestingMap.Remove(HttpRequest->GetURL());
}

void UHotChunkJsonHttp::OnRequestProgress(FHttpRequestPtr HttpRequest, int32 BytesSent, int32 BytesReceived)
{
	TSharedPtr<FHotChunkJsonHttpRequest> HotChunkJsonHttpRequest = *RequestingMap.Find(HttpRequest->GetURL());
	HotChunkJsonHttpRequest->JsonHttpProgress.Broadcast(HttpRequest, BytesSent, BytesReceived);
}
